package com.android.jr_infraredcamera.utils

import android.util.Log
import java.io.BufferedReader
import java.io.DataInputStream
import java.io.DataOutputStream
import java.io.IOException
import java.io.InputStreamReader


/**
 * @author 战神族灬小火
 * @date 2023/4/28
 * @description
 */
object Adb {
    private const val TAG = "===Adb==="
    private val result = StringBuilder()
    private var mHaveRoot = false

    /**
     * 执行命令并且输出结果
     */
    fun execRootCmd(cmd: String): String? {
        //  return  BaijieManager.getInstance().setSocket(cmd)
        //  return  executeCommand(cmd)
        var result: String? = ""
        var dos: DataOutputStream? = null
        var dis: DataInputStream? = null
        try {
            val p = Runtime.getRuntime().exec("su") // 经过Root处理的android系统即有su命令
            dos = DataOutputStream(p.outputStream)
            dis = DataInputStream(p.inputStream)
            Log.i(TAG, cmd)
            dos.writeBytes(
                """
                $cmd
                
                """.trimIndent()
            )
            dos.flush()
            dos.writeBytes("exit\n")
            dos.flush()
            var line: String? = null
            while (dis.readLine().also { line = it } != null) {
                Log.d(TAG, "result=$line")
                result += line
            }
            p.waitFor()
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            if (dos != null) {
                try {
                    dos.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
            if (dis != null) {
                try {
                    dis.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
        return result

    }


    fun execRootCmdSilent2(cmd: String): Int {
        return try {
            val process = Runtime.getRuntime().exec(arrayOf("su", "-c", cmd))
            process.waitFor()
        } catch (e: Exception) {
            Log.e(TAG, "Error executing command ,$e")
            -1
        }
    }

    /**
     * 执行命令但不关注结果输出
     */
    fun execRootCmdSilent(cmd: String): Int {
        executeCommand(cmd)
        return 1
    }

    private fun executeCommand(command: String): String {
        val output = StringBuilder()
        try {
            val process = Runtime.getRuntime().exec(command)
            val reader = BufferedReader(InputStreamReader(process.inputStream))
            var line: String?
            while (reader.readLine().also { line = it } != null) {
                output.append(line).append("\n")
            }
            reader.close()
            process.waitFor()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return output.toString()
    }
}